package com.xszx.service;

import com.xszx.dao.GoodDao;
import com.xszx.dao.WarehouseDao;
import com.xszx.entity.GoodInOutInfo;
import com.xszx.entity.Goods;
import com.xszx.entity.Position;
import com.xszx.entity.WarehouseRegionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class GoodService {
    @Autowired
    private GoodDao goodDao;
    @Autowired
    private WarehouseDao warehouseDao;
    //入库
    public String inWarehouse(GoodInOutInfo goodInOutInfo) {

        //获得仓库的id
        //goodInOutInfo.setWid(warehouseDao.getWidByWname(goodInOutInfo.getWname()));
        //通过货物批次去查货物信息
        List<Goods> goods = goodDao.getGoodsByCode(goodInOutInfo.getGbatch());
        //通过选中的仓位获取仓位详细信息
        // 通过选中的仓位ID数组获取每个仓位的详细信息
        int space = 0;
        List<Position> allPositions = new ArrayList<>(); // Store all positions
        int area = goods.get(0).getArea() * goodInOutInfo.getGnum();

        if (goodInOutInfo.getPositionIds() != null && goodInOutInfo.getPositionIds().length > 0) {
            for (int i = 0; i < goodInOutInfo.getPositionIds().length; i++) {
                int positionId = goodInOutInfo.getPositionIds()[i];
                List<Position> positions = warehouseDao.getpositionList(positionId);

                if (positions == null || positions.isEmpty()) {
                    System.out.println("警告: 仓位ID " + positionId + " 不存在或没有返回仓位信息");
                    continue;
                }else{
                    // Assuming we want the first position from the list
                    Position currentPosition = positions.get(0);
                    allPositions.add(currentPosition);

                    System.out.println(currentPosition.getSpace());
                    space += currentPosition.getSpace();
                }
                if (space >= area && i - goodInOutInfo.getPositionIds().length > 0) {
                    return "选的仓位太多，不合理，请取消仓位";
                }
            }

            if(space < area){
                return "选的仓位太少，放不下需要入库的货物，在此基础上请多选仓位";
            }
        }
        //通过区域的id查询区域信息
        WarehouseRegionInfo warehouseRegionInfo = goodDao.getRegionById(goodInOutInfo.getId());
        System.out.println(warehouseRegionInfo.getR_code());
        goodInOutInfo.setRcode(warehouseRegionInfo.getR_code());
        //入库，往入库记录表添加数据
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String time = formatter.format(date);
        goodInOutInfo.setTime(time);
        goodDao.addInMid(goodInOutInfo);
        System.out.println("入库成功");
        //修改货物的入库数量和状态（根据货物批次）
        System.out.println(goods.get(0).getNowNum()+"  "+goods.get(0).getInitNum());
        if(goods.get(0).getNowNum() == goods.get(0).getInitNum()+goodInOutInfo.getGnum()){
            //则需要修改状态（已入库）
            goodDao.updateGoods(goodInOutInfo.getGbatch(),goods.get(0).getNowNum());
        }else{
            //则需要修改入库数量
            goodDao.updateGoodsByInitNum(goodInOutInfo.getGbatch(),goods.get(0).getInitNum()+goodInOutInfo.getGnum());
        }
        //更新区域类型可用面积（注意入库减去面积的规则）修改使用状态，加入货物批号
        // 更新区域面积时使用 allPositions
        for (int y = 0; y < allPositions.size(); y++) { // 注意：这里用 allPositions.size() 而不是 positionIds.length
            Position currentPos = allPositions.get(y);
            int newArea = Math.min(currentPos.getSpace(), area);
            if (newArea == currentPos.getSpace()) {
                goodDao.updapeSpace(currentPos.getId(),goodInOutInfo.getGbatch());
                area -= newArea;
            } else if (newArea < currentPos.getSpace()) {
                goodDao.updapeSpac(currentPos.getId(), newArea - currentPos.getSpace(),  goodInOutInfo.getGbatch());
            }
        }
        Goods good = goods.get(0);
        System.out.println("货物信息: " + goods);

        // 3. 检查货物状态（新增状态检查）
        if(good.getState().equals("已入库")) {
            // 计算存货时长
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // 将int时间戳转换为Date对象
                long timestamp = good.getTime() * 1000L; // 假设getTime()返回的是秒级时间戳
                Date inTime = new Date(timestamp);

                // 计算存货时长（天数）
                long diffDays = (System.currentTimeMillis() - inTime.getTime()) / (1000 * 60 * 60 * 24);
                String state = "";
                if(diffDays >= 30) {
                    // 超过30天，状态改为逾期
                    state = "逾期";
                    goodDao.updateGoodsState(goodInOutInfo.getGbatch(), state);
                    return "货物已逾期，不能入库";
                } else if(diffDays >= 27) { // 剩余3天
                    // 剩余3天，状态改为快逾期
                    state = "快逾期";
                    goodDao.updateGoodsState(goodInOutInfo.getGbatch(), state);
                }
          }
        return "入库成功";
    }

    //获得入库记录（信息）
    public List<GoodInOutInfo> getInWarehouseRecord() {
        return goodDao.getInWarehouseRecord();
    }
    //出库
    public String outWarehouse(Integer gid, Integer num) {
        int ret = goodDao.outWarehouse(String.valueOf(gid), num); //减去数量
        if (ret == 1) {//更新出库记录表
            //获得批次
            String code = goodDao.getCodeById(String.valueOf(gid));
            //获得这一批次的货物数量
            Integer gnum = goodDao.getGnumByCode(code);
            System.out.println("gnum"+gnum);
            if(gnum == 0){
                goodDao.updateGoodsState(code, "已出库");
            }
            //获得这一批次的货物存放在哪个仓库
            String wid = goodDao.getWidByGcode(code);
            System.out.println("wid"+wid);
            //获得这一批次的货物放在哪个区域
            String number = goodDao.getGNumberBycode(code);
            System.out.println("number"+number);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String time = formatter.format(date);
            //往中间表中添加记录
            goodDao.addOutMid(wid, number, code, time, num);
            //还应该在区域类型表加上面积
            //先查询该货物的单个面积
            Integer area=goodDao.getAreaByGid(String.valueOf(gid));
            System.out.println("area"+area);
            // 2. 计算总释放面积 = 单个面积 * 出库数量
            int totalReleaseArea = num * area;
            System.out.println("totalReleaseArea" + totalReleaseArea);
            //去查这批货物放在哪个区域类型里
            List<Position> positions = goodDao.getPositionList(code);
            System.out.println("positions" + positions);
            if (positions == null || positions.isEmpty()) {
                return "未找到货物所在的仓位";
            }
            // 遍历仓位并更新可用面积
            int remainingArea = totalReleaseArea;
            // 5. 遍历仓位进行面积释放
            for (Position position : positions) {
                if (remainingArea <= 0) {break;}

                // 计算当前仓位已占用的面积
                int occupiedArea = position.getArea() - position.getSpace();

                // 计算可释放面积（不能超过需要释放的剩余面积和当前仓位占用面积）
                int releasableArea = Math.min(occupiedArea, remainingArea);

                if (releasableArea <= 0) {continue;}

                // 计算释放后的新可用面积
                int newSpace = position.getSpace() + releasableArea;

                if (newSpace == position.getArea()) {
                    // 情况1：完全释放（仓位变为完全空闲）
                    goodDao.releasePosition(position.getId(), newSpace);
                    System.out.println("仓位已释放：{}" + position.getId());
                } else {
                    // 情况2：部分释放
                    goodDao.increasePositionSpace(position.getId(), newSpace);
                    System.out.println("仓位部分释放：{}" + position.getId());
                }
                remainingArea -= releasableArea;
            }
            // 5. 检查是否完全释放
            if (remainingArea > 0) {
                System.err.println("警告：货物理论释放面积未完全处理，剩余: {}" + remainingArea);
            }
//            goodDao.addArea(wid,number,area);

            //还应该看看仓库中是否有货物，如果没有货物了那么就设置为空闲（返回0代表空）
            Integer flag = goodDao.isEmpty(Integer.parseInt(wid));
            if(flag==0){
                warehouseDao.updateWarehouseState(Integer.parseInt(wid),"空闲");
            }
            return "出库成功";
        }
        return "出库失败";
    }
    //获得出库记录
    public List<GoodInOutInfo> getOutWarehouseRecord() {
        return goodDao.getOutWarehouseRecord();
    }



}